<template>
  <view class="index-box">
    <view v-if="bannerList.length" class="banner-box">
      <uni-swiper-dot
          class="uni-swiper-dot-box"
          :current="currentBannerIndex"
          :info="bannerList"
          field="name"
          :dotsStyles="{ backgroundColor: 'rgba(255, 255, 255, 0.3)', selectedBackgroundColor: '#fff' }">
        <swiper class="swiper-box" @change="bannerChange($event)">
          <swiper-item v-for="item in bannerList" :key="item.key">
            <view class="swiper-item">
              <image class="banner-img" :src="item.picturePath" mode="aspectFill"></image>
            </view>
          </swiper-item>
        </swiper>
      </uni-swiper-dot>
    </view>
    <view class="my-project-box">
      <view class="project-title">
        <view class="title-content">
          <view class="iconfont icon-folder"></view>
          落地项目：
          <view class="project-count">{{ landingProjectCount }}</view>
        </view>
        <view class="more" @click="toMore()">
          更多
          <view class="iconfont icon-arrow-right"></view>
        </view>
      </view>
      <view class="detail-box">
        <view class="detail-item info">
          <view class="item-icon iconfont icon-lamp"></view>
          <view class="item-desc">灯具总数</view>
          <view class="item-count">{{ lampTotalCount }}</view>
        </view>
        <view class="detail-item danger">
          <view class="item-icon iconfont icon-warning"></view>
          <view class="item-desc">故障数量</view>
          <view class="item-count">{{ lampWarningCount }}</view>
        </view>
        <view class="detail-item info">
          <view class="item-icon iconfont icon-lighting"></view>
          <view class="item-desc">累计用电(Kwh)</view>
          <view class="item-count">{{ powerTotal }}</view>
        </view>
        <view class="detail-item success">
          <view class="item-icon iconfont icon-recycle"></view>
          <view class="item-desc">节能率(%)</view>
          <view class="item-count">{{ savingRate }}</view>
        </view>
        <view class="detail-item success">
          <view class="item-icon iconfont icon-leaf"></view>
          <view class="item-desc">累计降碳(T)</view>
          <view class="item-count">{{ carbonReduction }}</view>
        </view>
        <view class="detail-item success">
          <view class="item-icon iconfont icon-lighting"></view>
          <view class="item-desc">累计节电(Kwh)</view>
          <view class="item-count">{{ powerSaving }}</view>
        </view>
      </view>
    </view>
    <view class="feature-box">
      <view class="feature-item" @click="toProjectList()">
        <view class="feature-icon">
          <text class="iconfont icon-project-line"></text>
        </view>
        <view class="feature-content">
          <view class="feature-name">
            我的项目<text v-if="myProjectCount" class="project-count">({{ myProjectCount }})</text>
          </view>
        </view>
      </view>
      <view class="feature-item" @click="toTestCalculate()">
        <view class="feature-icon">
          <text class="iconfont icon-calc-line"></text>
        </view>
        <view class="feature-content">
          <view class="feature-name">测算工具</view>
        </view>
      </view>
      <view class="feature-item" @click="toHelpCenter()">
        <view class="feature-icon">
          <text class="iconfont icon-doc-line"></text>
        </view>
        <view class="feature-content">
          <view class="feature-name">文档中心</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import mixin from '@/mixins/index.js'
import { CONFIG } from '@/envs/_/config'
import { USER_ROLE } from '@/constant/index.js'
import { getImagePath, formatPhone, getCarbonReductionByPower, fixedDecimal, formatUserCode } from '@/utils/index.js'
import cms from '@/utils/cms.js'
export default {
  mixins: [mixin],
  data() {
    return {
      isAdmin: false,
      canEdit: false,
      userInfo: '',
      userName: '',
      userNameShow: '',
      phoneNumber: '',
      phoneNumberShow: '',
      userCode: '',
      userIcon: '',
      landingProjectCount: 0,
      myProjectCount: 0,
      intentionProjectCount: 0,
      testProjectCount: 0,
      lampTotalCount: 0,
      lampWarningCount: 0,
      powerTotal: 0,
      powerSaving: 0,
      savingRate: 0,
      carbonReduction: 0,
      bannerList: [],
      currentBannerIndex: 0
    }
  },
  onShow() {
    this.getUserInfo()
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  onPullDownRefresh() {
    this.getUserInfo()
  },
  mounted() {
    this.getUserInfo()
    this.getProjectType()
    this.getLampType()
    this.getAppBanners()
    if (this.params.gatewayId) {
      this.toProjectList(this.params.gatewayId)
    } else if (this.params.videoId) {
      this.toHelpCenter(this.params.videoId)
    } else if (this.params.projectId) {
      this.toProjectList()
    }
  },
  methods: {
    getUserInfo() {
      const self = this
      uni.request({
        url: '/user/get',
        success(result) {
          if (result.data.success && result.data.data) {
            const userInfo = result.data.data
            self.userInfo = userInfo
            self.isAdmin = userInfo.role === USER_ROLE.ADMIN
            self.canEdit = [USER_ROLE.ADMIN, USER_ROLE.AGENT].includes(userInfo.role)
            self.userName = userInfo.name || ''
            self.userNameShow = self.userName || '未设置昵称'
            self.phoneNumber = userInfo.phone || ''
            self.phoneNumberShow = formatPhone(self.phoneNumber)
            self.userCode = formatUserCode(userInfo.id)
            self.userIcon = getImagePath(userInfo.photo)
            self.myProjectCount = Math.ceil(userInfo._project_count) || 0
            if (userInfo.department_id) {
              self.getDepartmentData()
            } else {
              self.setCountInfo(userInfo)
            }
            self.$forceUpdate()
            uni.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
          }
        }
      })
    },
    getDepartmentData() {
      const self = this
      uni.request({
        url: '/department/get',
        data: {
          id: self.userInfo.department_id,
        },
        success(result) {
          if (result.data.success && result.data.data) {
            const data = result.data.data
            self.setCountInfo(data)
          }
        },
        complete() {
          uni.stopPullDownRefresh()
        }
      })
    },
    setCountInfo(data) {
      const self = this
      self.landingProjectCount = Math.ceil(data._project_count) || 0
      self.lampTotalCount = Math.ceil(data._node_count) || 0
      self.lampWarningCount = Math.ceil(data._error_count) || 0
      self.powerTotal = fixedDecimal(data._KWh, 1) || 0
      self.savingRate = fixedDecimal(data._rate, 1) || 0
      self.powerSaving = fixedDecimal((self.powerTotal * self.savingRate) / (100 - self.savingRate), 1)
      self.carbonReduction = getCarbonReductionByPower(self.powerSaving)
    },
    getAppBanners() {
      const self = this
      const target = cms.graphQL.queryBanners
      uni.request({
        url: target.url,
        method: 'POST',
        data: {
          query: target.query,
          variables: {
            appid: CONFIG.WX_APPID,
          },
        },
        success(result) {
          if (Array.isArray(result.data?.data?.[target.column])) {
            const arr = []
            result.data.data[target.column].forEach(item => {
              const bannerItem = {
                name: item.name || '',
                key: item.id,
                picturePath: getImagePath(item.image?.publicUrl)
              }
              arr.push(bannerItem)
            })
            self.bannerList = arr
          }
        },
        complete() {
          uni.stopPullDownRefresh()
        }
      })
    },
    bannerChange(e) {
      this.currentBannerIndex = e.detail.current
    },
    getProjectType() {
      const self = this
      uni.request({
        url: '/sys/xm_type',
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            result.data.data.forEach(item => {
              const typeItem = {
                key: item.code,
                code: item.code,
                name: item.name || '',
                value: item.code,
                text: item.name || ''
              }
              arr.push(typeItem)
            })
            uni.setStorage({
              key: 'projectType',
              data: JSON.stringify(arr)
            })
          }
        }
      })
    },
    getLampType() {
      const self = this
      uni.request({
        url: '/sys/light_type',
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            result.data.data.forEach(item => {
              const typeItem = {
                key: item.code,
                code: item.code,
                name: item.name || '',
                value: item.code,
                text: item.name || ''
              }
              arr.push(typeItem)
            })
            uni.setStorage({
              key: 'lampType',
              data: JSON.stringify(arr)
            })
          }
        }
      })
    },
    toUserInfoSetting() {
      uni.navigateTo({
        url: '/pages/me/edit-info/edit-info'
      })
    },
    toMore() {
      if (this.userInfo.department_id) {
        uni.navigateTo({
          url: `/pages/index/distribution/distribution`
        })
      } else {
        this.toProjectList()
      }
    },
    toProjectList(gatewayId = null) {
      uni.navigateTo({
        url: `/pages/index/project-list/project-list${gatewayId ? `?gatewayId=${gatewayId}` : ''}`
      })
    },
    toPreProjectList() {
      uni.navigateTo({
        url: '/pages/index/pre-project-list/pre-project-list'
      })
    },
    toTestProjectList() {
      uni.navigateTo({
        url: '/pages/index/test-project-list/test-project-list'
      })
    },
    toTestCalculate() {
      uni.navigateTo({
        url: '/pages/index/test-calculate/test-calculate'
      })
    },
    toHelpCenter(videoId) {
      uni.navigateTo({
        url: `/pages/me/help-list/help-list${videoId ? `?videoId=${videoId}` : ''}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.index-box {
  padding: 30rpx;
  .banner-box {
    margin-bottom: 30rpx;
    border-radius: 10rpx;
    .swiper-box {
      height: 230rpx;
    }
    .banner-img {
      border-radius: 10rpx;
      width: 690rpx;
      height: 230rpx;
    }
  }
  .my-project-box {
    margin-bottom: 30rpx;
    position: relative;
    z-index: 2;
    background-color: $white;
    border-radius: 10rpx;
    padding: 30rpx;
    .project-title {
      display: flex;
      justify-content: space-between;
      .title-content {
        font-size: $font-size-5;
        display: flex;
        align-items: center;
        .iconfont {
          font-size: 38rpx;
          margin-right: 20rpx;
          color: $primary;
        }
        .project-count {
          color: $primary;
        }
      }
      .more {
        display: flex;
        align-items: center;
        font-size: $font-size-3;
        color: $primary;
      }
    }
    .detail-box {
      margin-top: 24rpx;
      background-color: $background-light;
      border-radius: 10rpx;
      display: flex;
      flex-wrap: wrap;
      .detail-item {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        border-right: 2rpx solid $border-lighter;
        padding-top: 16rpx;
        &:nth-child(3n) {
          border-right-color: transparent;
        }
        &:nth-child(n + 4) {
          border-top: 2rpx solid $border-light;
        }
        width: 211rpx;
        height: 203rpx;
        color: #888;
        .item-icon {
          font-size: 44rpx;
        }
        .item-desc {
          margin-top: 8rpx;
          font-size: $font-size-1;
        }
        .item-count {
          margin-top: 4rpx;
          font-size: $font-size-5;
        }
      }
    }
  }
  .feature-box {
    margin-bottom: 30rpx;
    display: grid;
    grid-template-columns: repeat(3, 220rpx);
    grid-gap: 15rpx;
    .feature-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 20rpx 4rpx;
      width: 220rpx;
      height: 180rpx;
      background-color: $white;
      border-radius: 10rpx;
      .feature-icon {
        font-size: 72rpx;
        color: #888;
      }
      .feature-content {
        .feature-name {
          font-size: $font-size-3;
        }
        .project-count {
          color: $primary;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
